import regeneratorRuntime from '../../plugins/regenerator-runtime.js'
import { addVisitorFrequency } from '../../utils/encapsulation.js'//数据监控
import { Request_API_CN, Request_API_COM } from '../../utils/index.js'//封装请求
import login from '../../api/login.js';
import { prefix, surface } from '../../api/config.js';
import promisefy from '../../plugins/promise.util.js';//生成canvas
const app = getApp();
let _this
Page({
  data:{
    maiClub:[
      { src: "https://www.qiff.club/WeChat/Lipstick/user/mai-club-1.png", name: '分销明细', url: "/pages/user-dist/user-dist"},
      { src: "https://www.qiff.club/WeChat/Lipstick/user/mai-club-2.png", name: '提现记录', url: "/pages/user-record/user-record"},
      { src: "https://www.qiff.club/WeChat/Lipstick/user/mai-club-3.png", name: '我的团队', url: "/pages/user-team/user-team"},
      { src:"https://www.qiff.club/WeChat/Lipstick/user/mai-club-4.png",name:'生成海报'},
    ],
    avatar:'',//头像
    nickname:"",//名称
    codeurl:'',//个人专属二维码
    Canvas:false,//画布
    balance:'',//金额
    grade:'',//个人等级
    icon:'',//是否显示分销
    mylipstick:"",//我的口红数量
    weixin1:'',//客服联系方式
    weixin2:'',//商务合作联系方式
    commission:''//佣金
  },
  onLoad:function(){
    _this = this;
    _this.getSystem();//动态获取屏幕尺寸
    _this.lipstickShare();//分享图片
  },
  onShow:function(){
    wx.showLoading({
      mask: true,
    })
    _this.authorize();
  },
  userData:()=>{//个人中心数据
    // Request_API_CN('/lipstick/personCenter', 'POST', { openid: 'o1IkB5Zd9bAAP_6pTEwV6sFuAdqc' })
    Request_API_CN(prefix+'/personCenter', 'POST', { openid: app.globalData.openid })
    .then((res)=>{
      console.log(res.data.data)
      _this.setData({
        avatar: res.data.data.avatar,
        nickname: res.data.data.nickname,
        balance: res.data.data.balance,
        grade: res.data.data.grade == 1 ? '初级会员' : (res.data.data.grade==2?'中级会员':'高级会员'),
        icon: res.data.data.icon,
        // icon: true,
        mylipstick: res.data.data.mylipstick,
        weixin1: res.data.data.weixin1,
        weixin2: res.data.data.weixin2,
        commission: res.data.data.commission,
        
      })

      
    })
  },
  Address:()=>{// 收货地址
    wx.chooseAddress({
      success:(res)=>{
        console.log(res.provinceName, res.cityName, res.countyName, res.detailInfo)
        console.log(res.userName)
        console.log(res.telNumber)
        console.log(res.postalCode)
      },
      fail: (res) => {
        wx.getSetting({
          success: res => {
            var statu = res.authSetting;
            if (!statu['scope.userLocation']) {
              wx.openSetting({
                success: res => {
                  console.log(res)
                }
              })
            }
          }
        })
      }
    })
  },
  forward:()=>{//提现
    
    if (_this.data.commission >= 5) {

      wx.navigateTo({
        url: "/pages/user-put/user-put?commission=" + _this.data.commission
      })

     


    } else {
      wx.showToast({
        title: "最低提现金额5元！",
        icon: "none",
        mask: true,
        duration:5000
      })
    }


  },
  copyText: (e) => { wx.setClipboardData({ data: e.currentTarget.dataset.text }); },//一键复制 
  startBtn: () => { _this.authorize() },//点击判断
  authorize: () => {//判断用户是否授权
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          _this.setData({ user: false });
          console.log('没有授权')
        } else {
          _this.setData({ user: true })
          console.log('授权')
          wx.getUserInfo({
            success: (res) => {
              _this.userInfo(res.userInfo)
             
            }
          })
        }
        wx.hideLoading() 
      }
    })
  },
  tapCancas:()=>{//点击保存海报
    wx.showLoading({
      mask: true,
      title: '正在保存到相册...'
    })
    const wxGetImageInfo = promisefy.promisify(wx.getImageInfo)
    
    console.log(1)
    Request_API_CN(prefix+'/makeCode', 'POST', { openid: app.globalData.openid })
    // Request_API_CN('/lipstick/makeCode', 'POST', { openid: 'o0sdJ5APDCv3LsHiuzS25pDaNRIE' })
    .then((res)=>{
      let path = {}
      console.log(2)
      console.log(res.data.data.codeurl)


      wx.getImageInfo({
        src: 'https://www.qiff.club/WeChat/Lipstick/user/codeUrl.jpg',
        success: (data1) => {
          path.A = data1.path
          console.log(3)
          wx.getImageInfo({
            src: res.data.data.codeurl,
            success: (data2) => {
              path.B = data2.path
              _this.canvas(path)
              console.log(4)
            },
            fail:()=>{
              wx.hideLoading({})
            }
          })
        }
      })
      
      
      _this.setData({
        codeImg: res.data.data.codeurl,
        Canvas: true
      })
    }) 
  },
  canvas: (path)=>{//生成个人专属二维码
  
    
    console.log(5)
    let BJURL = path.A;//背景图片
    let Code = path.B;
    let codeSize = _this.data.width<=320?100:150;//二维码大小
    let bottom = _this.data.width <= 320 ? 180 : 250;
    const ctx = wx.createCanvasContext('Canvas')
    ctx.drawImage(BJURL, 0, 0, _this.data.width, _this.data.height)//生成banner背景图片
    console.log(6)
    ctx.drawImage(Code, (_this.data.width / 2) - (codeSize / 2), _this.data.height - bottom, codeSize, codeSize);
    //生成banner背景图片
    console.log(7)
    ctx.draw();//画布渲染完毕
    console.log(8)
    const wxCanvasToTempFilePath = promisefy.promisify(wx.canvasToTempFilePath)  //当前画布生成图片
    const wxSaveImageToPhotosAlbum = promisefy.promisify(wx.saveImageToPhotosAlbum) //保存到相册
    console.log(9)
    wxCanvasToTempFilePath({
      canvasId: 'Canvas'
    }, this)
      .then(res => {
        console.log(10)
        wx.setStorageSync('Canvas', res.tempFilePath)
        wx.hideLoading({})
        return wxSaveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          fail:(res)=>{
            console.log(res)
          }
        })
      })
      .then(res => {
        console.log(res)
        
        wx.showToast({
          title: '已保存到相册'
        })
      })
  },
  getSystem: () => {//获取屏幕尺寸，动态渲染canvas
    wx.getSystemInfo({
      success: (res) => {
        _this.setData({
          height: res.windowHeight,
          width: res.windowWidth
        })
      }
    })
  },
  userInfo: (e) => {//提交用户信息
    let obj = {}
    obj.openid = app.globalData.openid;
    obj.nickname = e.nickName;
    obj.gender = e.gender;
    obj.city = e.city;
    obj.province = e.province;
    obj.avatar = e.avatarUrl;
    obj.aid = app.globalData.AID ? app.globalData.AID : '';
    obj.tablename = surface;
    // console.log(obj)
    obj.inviterOpenid = app.globalData.inviterOpenid ? app.globalData.inviterOpenid:''
    console.log('提交用户信息')
    wx.setStorageSync('userInfo', obj)
    Request_API_CN('/currency/firstLogin', 'POST', { openid: app.globalData.openid, tablename: surface })
      .then((res) => {
        
        console.log(res)
        if (res.data.data.isFirstLogin == 1) {
          Request_API_CN('/currency/userInfo', 'POST', obj)
        }
        setTimeout(() => { _this.userData();},100)
      })
    // 
  },
  lipstickShare:()=>{//分享数据
    Request_API_CN(prefix + '/lipstickShare', 'POST', { openid: app.globalData.openid, tablename: surface })
      .then((res) => {
        _this.setData({
          imgurl: res.data.data.imgurl,
          title: res.data.data.title
        })
      })
  },
  onShareAppMessage: (e) => {
    return {
      path: '/pages/index/index?inviterOpenid=' + app.globalData.openid,
      title: _this.data.title,
      imageUrl: _this.data.imgurl
    }
  }
})